package com.ebupt.migu.music.autoTri.Service.Impl;

import com.ebupt.migu.music.autoTri.Entity.SingerBlackListBean;
import com.ebupt.migu.music.autoTri.Mapper.SingerBlackListMapper;
import com.ebupt.migu.music.autoTri.Service.SingerBlackListService;
import com.ebupt.migu.music.common.entity.Page;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MiguRuntimeException;
import com.ebupt.migu.music.common.util.CSVUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.text.html.Option;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author xuhongsong
 * @version 1.0
 * @date 2020/10/10 15:59
 */
@Service
@Slf4j
public class SingerBlackListServiceImpl implements SingerBlackListService {

    @Autowired
    private SingerBlackListMapper singerBlackListMapper;

    /**
     *  新增歌手黑名单
     * @return
     */
    @Override
    public void add(SingerBlackListBean singerBlackListBean) {
        switch (singerBlackListBean.getType()){
            case 1:
                Optional.ofNullable(singerBlackListBean).ifPresent((value) -> {
                    singerBlackListBean.setCreateUser(singerBlackListBean.getCreateUser());
                    singerBlackListBean.setUpdateUser(singerBlackListBean.getUpdateUser());
                    singerBlackListMapper.add(singerBlackListBean);
                });
                break;
            case 2:
           //     Optional.ofNullable(singerBlackListBean).map(u-> u.getCsvUrl()).ifPresent((value) -> {
                    List<String[]> records = CSVUtils.csvRead(singerBlackListBean.getCsvUrl(), ',');
                    // 去掉最顶上一行
                    List<String[]> recordsList =records.subList(1,records.size());
                    if (!IsRight(records)){
                        log.info("模板不正确!");
                        throw new MiguRuntimeException("模板不正确!");
                    }
                    List<SingerBlackListBean> listBeans= recordsList.stream().map(
                            e->new SingerBlackListBean(resultSingerId(e[0]),e[1],e[2], 2,singerBlackListBean.getCsvUrl(),singerBlackListBean.getCreateUser(),singerBlackListBean.getUpdateUser(),singerBlackListBean.getCreatorId(),singerBlackListBean.getCreatorDepartment())
                    ).collect(Collectors.toList());
                    //  去掉歌手名称为空的
                    List<SingerBlackListBean> lists = listBeans.stream().filter(s-> StringUtils.isNotBlank(s.getSingerName())).collect(Collectors.toList());
                    // 去重 并且要全是数字
                    List<SingerBlackListBean> list = lists.stream().filter(s-> isNumeric(s.getSingerId())==true).collect(Collectors.toList());
                    if (list!=null && !list.isEmpty()) {
                        singerBlackListMapper.insertBatchSingerBlackList(list);
                    }
            //    });
                break;
        }

    }

    /**
     *  判断是否为空
     * @return
     */
    private Long resultSingerId(String str){
      return   "".equals(str)?0:Long.parseLong(str);
    }
    /**
     *
     * @return
     */
    private  Boolean  IsRight(List<String[]> records){
        String[] strings =records.get(0);
        if ("歌手id".equals(strings[0]) && "歌手名称".equals(strings[1]) && "备注".equals(strings[2])) {
         return  true;
        }
        return false;
    }
    /**
     *   删除黑名单
     * @param dataIds
     * @return
     */
    @Override
    public int delete(String[] dataIds,String createUser){
        Map<String,Object>   map=new HashMap<>();
        map.put("updateUser",createUser);
        switch (dataIds.length){
            case 1:
                  map.put("dataId",dataIds[0]);
                  break;
              default:
                  map.put("array",dataIds);
                  break;
        }
        return  dataIds.length==1?singerBlackListMapper.updateStatus(map):singerBlackListMapper.batchUpdateStatus(map);
    }

    @Override
    public ResultObject queryMap(Map<String,Object> params) {
        ResultObject<Page<HashMap<String, Object>>> res = new ResultObject<>();
        // 是否超级管理员 1-超级管理员； 0-普通用户；
        String is_admin = params.get("isAdmin").toString();
        if ("1".equals(is_admin)){
            params.remove("creatorDepartment");
        }
        // 总数
        Integer total = singerBlackListMapper.total(params);
        // 分页查询结果集
        List<HashMap<String, Object>> datas = singerBlackListMapper.SingerBlackListBeanList(params);
        // 分页
        Page<HashMap<String, Object>> page = new Page<>();
        page.setTotal(total);
        page.setData(datas);
        res.setData(page);
        return res;
    }

    /**
     * 判断是否是数字
     *
     * @param str
     * @return
     */
    private static boolean isNumeric(Object str) {
        //Pattern pattern = Pattern.compile("^-?[0-9]+"); //这个也行
        if (str!=null & str!="") {
            Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");//这个也行
            Matcher isNum = pattern.matcher(str.toString());
            if (!isNum.matches()) {
                return false;
            }
            return true;
        }
        return true;
    }






}
